<template>
  <div class="wrapper">
    <div class="charging_rules">
      <div class="rule_title">
        <span class="title-l"> <i class="icon_left"></i>{{ titleTip }} </span>
        <el-link @click="handleBack" class="icon-right" icon="el-icon-refresh-left" type="primary"> 返回上一页 </el-link>
      </div>
      <el-form ref="ruleForm" :model="ruleForm" :disabled="disable" :rules="rules" :inline="true" label-width="100px">
        <div class="range_tab">基本信息</div>
        <el-row :gutter="24">
          <el-form-item label="规则名称" prop="name">
            <el-input v-model="ruleForm.name"></el-input>
          </el-form-item>
          <el-form-item label="承运类型" prop="transport_type_id">
            <el-select v-model="ruleForm.transport_type_id" clearable filterable placeholder="请选择">
              <el-option v-for="item in transportTypeData" :label="item.name" :value="item.id * 1" :key="item.id">{{ item.name }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="计费方式" prop="_self_billing_way">
            <el-select v-model="ruleForm._self_billing_way" @change="handleWayChange" clearable filterable placeholder="请选择">
              <el-option v-for="item in patternData" :label="item.item_name" :value="item.item_code" :key="item.item_code">{{ item.item_name }}</el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="24">
          <el-form-item label="计费费项" prop="_self_pricing_range">
            <el-cascader v-model="ruleForm._self_pricing_range" class="price_input" @change="handleChangeLimit" :options="rangeData" :props="{ multiple: true }" clearable> </el-cascader>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-radio v-model="ruleForm.status" label="0">启用</el-radio>
            <el-radio v-model="ruleForm.status" label="1">禁用</el-radio>
          </el-form-item>
        </el-row>
        <div class="range_tab">应用范围</div>
        <el-form-item label="客户">
          <el-select v-model="ruleForm['applied_range'].customer_ids" multiple clearable filterable remote :remote-method="getCustomerData" placeholder="请选择">
            <el-option v-for="item in customerData" :label="item.name" :value="item.id * 1" :key="item.id"> {{ item.name }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="承运方">
          <el-select v-model="ruleForm['applied_range'].carrier_ids" multiple clearable filterable placeholder="请选择">
            <el-option v-for="item in carrierData" :label="item.name" :value="item.id * 1" :key="item.id"> {{ item.name }}</el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="包装型号">
          <el-select v-model="ruleForm['applied_range'].packing_type" multiple clearable filterable placeholder="请选择">
            <el-option v-for="item in packageData" :key="item.item_code" :label="item.item_name" :value="item.item_code * 1"></el-option>
          </el-select>
        </el-form-item>

        <!-- <br /> -->
        <!-- <div style="margin-top: 20px;padding-right:20px;text-align: right;padding-bottom:20px">
                    <el-button @click="handleBack">返回</el-button>
                    <el-button type="primary" @click="handleClickSubmit()">保存</el-button>
                </div> -->
        <div class="btn_save">
          <div class="btn_save_content">
            <el-button data-tracker="P44-7" type="primary" plain @click="handleClickSubmit()" size="medium">保存以上信息</el-button>
            <div style="padding-top: 5px">保存以上信息后，可进行阶梯区间费用配置</div>
          </div>
        </div>
        <template>
          <div class="range_tab">区间范围</div>
          <el-form-item label="计费区间">
            <el-select class="range_select" v-model="ruleForm['stepWay']" clearable filterable placeholder="请选择">
              <el-option v-for="item in stepData" :label="item.value" :value="item.key" :key="item.key"> {{ item.value }}</el-option>
            </el-select>

            <div class="range_input" v-for="(item, index) in ruleForm.rangeArr" :key="index">
              <!-- <div style="overflow:hidden;width:100%"> -->
              <div style="float: left">
                <el-input v-model="item.min_measure" disabled placeholder="0" />
                <!-- {{item.min_measure}} -->
                --
                <!-- {{item.max_measure}} -->
                <el-input v-model="item.max_measure" disabled placeholder="无穷大" />
              </div>
              <div style="float: left; margin-right: 10px; margin-left: 10px">
                <el-button type="primary" plain icon="el-icon-edit" circle @click="handleRangeChange('edit', index)"> </el-button>
                <el-button type="primary" plain icon="el-icon-delete" circle @click="handleRangeChange('delete', index)"> </el-button>
              </div>
            </div>

            <div class="range_icon">
              <!-- <el-button type="primary" plain icon="el-icon-plus" circle
                                @click="handleChangeRange('ADD')">
                            </el-button>
                            <el-button type="primary" plain icon="el-icon-minus" circle
                                @click="handleChangeRange('DELETE')">
                            </el-button> -->
              <el-button type="primary" plain icon="el-icon-plus" circle @click="handleRangeChange('add')"> </el-button>
            </div>
          </el-form-item>

          <div class="actions">
            <div class="left">
              <div style="padding-bottom: 10px">
                <el-button data-tracker="P44-8" type="primary" plain @click="handleClickAdd">新增</el-button>
                <el-button data-tracker="P44-9" type="primary" plain @click="handleClickDel">删除</el-button>
                <el-button data-tracker="P44-10" type="primary" plain @click="handleClickImport">导入 </el-button>
                <el-button data-tracker="P44-11" type="primary" plain @click="handleClickExport">导出 </el-button>
              </div>
            </div>
            <div class="right">
              <el-pagination :current-page="paginations.pageIndex" :page-sizes="paginations.pageSizes" :page-size="paginations.pageSize" :layout="paginations.layout" :total="paginations.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
          </div>
          <!-- :row-class-name="tableRowClassName" -->
          <el-table :data="priceList" :key="Math.random()" @selection-change="handleSelectionChange" style="width: auto" :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
            <el-table-column type="selection" width="55"> </el-table-column>
            <el-table-column fixed label="序号" width="50" type="index"></el-table-column>
            <el-table-column prop="date" label="出发区域" width="220">
              <template slot-scope="scope">
                <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                  <el-cascader :key="scope.row.area_id" :props="cascaderProps" filterable clearable :options="areaData" v-model="scope.row['start_area']" placeholder="请选择省市"></el-cascader>
                </template>
                <template v-else>
                  {{ scope.row["start_area_name"] }}
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="目的区域" width="220">
              <template slot-scope="scope">
                <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                  <el-cascader :key="scope.row.area_id" :props="cascaderProps" filterable clearable :options="areaData" v-model="scope.row['end_area']" placeholder="请选择省市"></el-cascader>
                </template>
                <template v-else>
                  {{ scope.row["end_area_name"] }}
                </template>
              </template>
            </el-table-column>

            <el-table-column prop="min_charges" label="基础费" width="220" v-if="isPackModel">
              <template slot-scope="scope">
                <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                  <el-input v-model="scope.row['min_charges']"> </el-input>
                </template>
                <template v-else>
                  {{ scope.row["min_charges"] }}
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="service_charge" label="服务费" width="220" v-if="isPackModel">
              <template slot-scope="scope">
                <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                  <el-input v-model="scope.row['service_charge']"> </el-input>
                </template>
                <template v-else>
                  {{ scope.row["service_charge"] }}
                </template>
              </template>
            </el-table-column>
            <el-table-column prop="return_incubator_fee_info" label="返箱费用信息" width="220" v-if="isPackModel">
              <el-table-column prop="min_value" label="首箱" width="140">
                <template slot-scope="scope">
                  <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                    <el-input v-model="scope.row['return_incubator_fee_info']['first_box_fee']"> </el-input>
                  </template>
                  <template v-else>
                    {{ scope.row["return_incubator_fee_info"]["first_box_fee"] }}
                  </template>
                </template>
              </el-table-column>
              <el-table-column prop="further_box_fee" label="续箱" width="140">
                <template slot-scope="scope">
                  <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                    <el-input v-model="scope.row['return_incubator_fee_info']['further_box_fee']"> </el-input>
                  </template>
                  <template v-else>
                    {{ scope.row["return_incubator_fee_info"]["further_box_fee"] }}
                  </template>
                </template>
              </el-table-column>
              <el-table-column prop="max_return_incubator_fee" label="最大返箱费" width="140">
                <template slot-scope="scope">
                  <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                    <el-input v-model="scope.row['return_incubator_fee_info']['max_return_incubator_fee']"> </el-input>
                  </template>
                  <template v-else>
                    {{ scope.row["return_incubator_fee_info"]["max_return_incubator_fee"] }}
                  </template>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column prop="address" :label="rangeText(index)" v-for="(rangeItem, index) in getRangeArr()" :key="index">
              <!-- <template slot-scope="scope"> -->
              <el-table-column prop="address" width="300" :label="getCostName(indey)" v-for="(priceItem, indey) in ruleForm.pricing_range" :key="indey">
                <template v-if="isFixedPrice">
                  <el-table-column prop="based_on_price" label="一口价" width="140">
                    <template slot-scope="scope">
                      <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                        <el-input v-model="getLadderPriceItem(scope, index, indey, priceItem)['based_on_price']"> </el-input>
                      </template>
                      <template v-else>
                        {{ getLadderPriceItem(scope, index, indey, priceItem)["based_on_price"] }}
                      </template>
                    </template>
                  </el-table-column>
                </template>
                <template v-else-if="isPackModel">
                  <el-table-column prop="based_on_price" label="费用" width="140">
                    <template slot-scope="scope">
                      <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                        <el-input v-model="getLadderPriceItem(scope, index, indey, priceItem)['further_price']"> </el-input>
                      </template>
                      <template v-else>
                        {{ getLadderPriceItem(scope, index, indey, priceItem)["further_price"] }}
                      </template>
                    </template>
                  </el-table-column>
                </template>
                <template v-else>
                  <el-table-column prop="first_measure" :label="firstMeasureText" width="140">
                    <template slot-scope="scope">
                      <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                        <el-input v-model="getLadderPriceItem(scope, index, indey, priceItem)['first_measure']"> </el-input>
                      </template>
                      <template v-else>
                        {{ getLadderPriceItem(scope, index, indey, priceItem)["first_measure"] }}
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column prop="based_on_price" label="首价" width="140">
                    <template slot-scope="scope">
                      <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                        <el-input v-model="getLadderPriceItem(scope, index, indey, priceItem)['based_on_price']"> </el-input>
                      </template>
                      <template v-else>
                        {{ getLadderPriceItem(scope, index, indey, priceItem)["based_on_price"] }}
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column prop="further_price" label="续价" width="140">
                    <template slot-scope="scope">
                      <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                        <el-input v-model="getLadderPriceItem(scope, index, indey, priceItem)['further_price']"> </el-input>
                      </template>
                      <template v-else>
                        {{ getLadderPriceItem(scope, index, indey, priceItem)["further_price"] }}
                      </template>
                    </template>
                  </el-table-column>
                </template>
              </el-table-column>
              <!-- </template> -->
            </el-table-column>
            <el-table-column prop="" label=""> </el-table-column>
            <el-table-column prop="" fixed="right" align="center" label="操作" width="140">
              <template slot-scope="scope">
                <template v-if="scope.row.rowMode === 'add' || scope.row.rowMode === 'edit'">
                  <el-button style="margin-right: 10px" type="text" plain size="mini" @click="handleClickOperation(scope.row, 'SAVE')">保存 </el-button>
                  <el-button style="margin-right: 10px" type="text" plain size="mini" @click="handleClickOperation(scope.row, 'CANCEL')">取消 </el-button>
                </template>
                <template v-else>
                  <el-button style="margin-right: 10px" type="text" plain size="mini" @click="handleClickOperation(scope.row, 'EDIT')">编辑 </el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
          <!-- <div style="margin-top: 20px;padding-right:20px;text-align: right;padding-bottom:20px">
                    <el-button @click="handleBack">返回</el-button>
                    <el-button type="primary" @click="handleClickSubmit()">保存</el-button>
                </div> -->
        </template>
      </el-form>
    </div>
    <ImportRules @import="handleImport" :downloadUrl="downloadUrl" :drawerfeesData="importDialogShow" @drawerfeesShow="drawerfeesFlagShowFn" />
    <el-dialog center title="" :visible.sync="dialogVisible" width="400px" :before-close="handleClose">
      <el-form label-width="100px" :model="rangeItem" ref="rangeItem" :rules="rulesRange">
        <el-form-item label="区间最小值" prop="min_measure" style="width: 250px">
          <el-input v-model="rangeItem.min_measure"></el-input>
        </el-form-item>
        <el-form-item label="区间最大值" prop="max_measure" style="width: 250px">
          <el-input v-model="rangeItem.max_measure"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRangeOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getTransportsList } from "@/api/waybill";
import { dictionanryList } from "@/page/material/common/common";
import { regionList } from "@/page/material/common/common";
import { carrierBox } from "@/api/waybill";
import { customerPeople } from "@/api/information";
import ImportRules from "./components/importRules.vue";
import {
  BillingRuleCreateFn,
  BillingRuleDetailFn,
  BillingRuleUpdateFn,
  BillingRuleImportFn,
  BillingRuleExportFn,
  BillingRulePriceListFn,
  BillingRulePriceAddFn,
  BillingRulePriceUpdateFn,
  BillingRulePriceDeleteFn,
  BillingRuleRangeCreate,
  BillingRuleRangeDelete,
  BillingRuleRangeUpdate,
} from "@/api/companymanagement";
export default {
  name: "chargingrules",
  components: { ImportRules },
  props: [],
  data() {
    return {
      dialogVisible: false,
      dialogMode: "",
      rangeItem: {},
      nowItem: {}, // 现在处理的区间
      importDialogShow: false,
      billingAreaPrice: [
        //     {
        //     ladder_range: [// 一个区间
        //         {
        //             ladder_price_list: [{}] // 一个费用项
        //         }
        //     ]
        // }
      ],
      ruleForm: {
        name: "", // 规则名称
        transport_type_id: "", // 承运类型
        billing_way: "", // 计费方式
        pricing_range: [], // 计费费项
        // time1: '',// 有效期
        rangeArr: [],
        status: "", //状态
        // 表格数据
        billing_area_price: [
          {
            ladder_range: [
              // 一个区间
              {
                ladder_price_list: [{}], // 一个费用项
              },
            ],
          },
        ],
        applied_range: {
          customer_ids: [], //客户
          carrier_ids: [], //承运商
          packing_type: [], //包装型号
        },
      },

      transportTypeData: [], //承运类型data
      patternData: [
        {
          item_code: "8",
          item_name: "包装数量",
        },
        {
          item_code: "1",
          item_name: "货物件数",
        },
        {
          item_code: "2",
          item_name: "体积",
        },
        {
          item_code: "3",
          item_name: "重量",
        },
        {
          item_code: "6",
          item_name: "一口价",
        },
      ], //计费方式data
      rangeData: [
        {
          value: 9,
          label: "运单",
          children: [
            {
              value: 1,
              label: "运费",
            },
          ],
        },
        {
          value: 1,
          label: "揽收",
          children: [
            {
              value: 25,
              label: "揽收提货费",
            },
            // {
            //     value: 26,
            //     label: '揽收包装费'
            // },
            // {
            //     value: 27,
            //     label: '揽收装卸费'
            // },
            // {
            //     value: 28,
            //     label: '揽收发货费'
            // }
          ],
        },
        {
          value: 3,
          label: "干线",
          children: [
            {
              value: 29,
              label: "运输费",
            },
          ],
        },
        {
          value: 4,
          label: "配送",
          children: [
            {
              value: 30,
              label: "基础配送费",
            },
            // {
            //     value: 31,
            //     label: '超区配送费'
            // }, {
            //     value: 32,
            //     label: '二次配送费'
            // }, {
            //     value: 33,
            //     label: '等待费'
            // }
          ],
        },
      ], // 计费范围
      areaData: [],
      customerData: [], // 客户
      carrierData: [], // 承运商下拉
      packageData: [], // 包装
      stepData: [
        {
          key: "9",
          value: "包装型号",
        },
        {
          key: "8",
          value: "包装数量",
        },
        {
          key: "1",
          value: "货物件数",
        },
        {
          key: "2",
          value: "体积",
        },
        {
          key: "3",
          value: "重量",
        },
        // {
        //     key: '4',
        //     value: '里程'
        // }
      ],
      cascaderProps: {
        // multiple: true,
        emitPath: true,
        checkStrictly: true,
        value: "id",
        label: "name",
        children: "next_level_data",
      },
      checkedRow: [],
      ladderPriceList: [],
      mode: "add",
      rules: {
        name: [{ required: true, message: "请填写规则名称", trigger: "blur" }],
        transport_type_id: [
          { required: true, message: "请选择承运类型", trigger: "change" },
        ],
        _self_billing_way: [
          { required: true, message: "请选择计费方式", trigger: "change" },
        ],
        // time1: [
        //     { required: true, message: "请填写有效期", trigger: "change" },
        // ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        _self_pricing_range: [
          { required: true, message: "请选择计费费项", trigger: "change" },
        ],
      },
      downloadUrl: "",
      priceList: [],
      paginations: {
        pageIndex: 1, // 当前位于哪页
        pageSize: 20, // 1页显示多少条
        pageSizes: [10, 20, 50, 100], //每页显示多少条
        total: 0,
        layout: "total, sizes, prev, pager, next, jumper", // 翻页属性
      },
      titleTip: "",
      rulesRange: {
        min_measure: [
          { required: true, message: "请填写区间最小值", trigger: "change" },
        ],
        max_measure: [
          { required: true, message: "请填写区间最大值", trigger: "change" },
        ],
      },
      obj: {},
    };
  },
  computed: {
    // 是否为一口价 true是
    isFixedPrice() {
      return this.ruleForm.billing_way === "6";
    },
    isPackModel() {
      return this.ruleForm['stepWay'] === "9";
    },
    // 首计量文案
    firstMeasureText() {
      const index = this.ruleForm["billing_way"];
      if (index === "8") {
        return "首个";
      }
      return ["", "首件", "首方", "首重"][index] || "首计量";
    },
    // 区间展示文案
    rangeText() {
      return function (index) {
        this.ruleForm.rangeArr = this.ruleForm.rangeArr || [];
        const rangeItem = this.ruleForm.rangeArr[index] || {};
        const { min_measure = "", max_measure = "" } = rangeItem;
        // 没有区间时文案
        if (min_measure === "" && max_measure === "") {
          return "";
        }
        if (min_measure * 1 === 0 && max_measure * 1 === 0) {
          return "";
        }
        const { value = "阶梯区间" } =
          this.stepData.find((item) => item.key === this.ruleForm["stepWay"]) ||
          {};
        return `${min_measure}≤${value}<${max_measure}`;
      };
    },
    disable() {
      return this.mode === "detail";
    },
  },
  mounted() {
    this.getDictionaryData();
    // 有id 编辑/详情
    if (this.$route.query.id) {
      this.getDetail();
    }
    if (this.$route.query.mode) {
      this.mode = this.$route.query.mode;
    }
    this.titleTip = this.getTitleTip();
  },
  methods: {
    getDetail() {
      BillingRuleDetailFn({ id: Number(this.$route.query.id) }).then((res) => {
        const data = res.data;
        // 获取客户id对应的数据
        customerPeople({
          ids: data["applied_range"].customer_ids,
          is_send: "1",
        }).then((res) => {
          this.customerData = res.data;
        });
        data._self_pricing_range = data.pricing_range;
        data._self_billing_way = data.billing_way;
        this.ruleForm = data;
        this.generateLadderPriceList();
        this.getPriceListFn();
      });
    },
    handleClose() {
      this.dialogVisible = false;
    },

    checkArea(row) {
      if (
        (row.start_area || []).length === 0 ||
        (row.end_area || []).length === 0
      ) {
        this.$message({
          message: "请填写出发区域和目的区域",
          type: "warning",
        });
        return false;
      }
      if ((row.start_area || []).length === 1) {
        this.$message({
          message: "出发区域需要详细到市或区",
          type: "warning",
        });
        return false;
      }
      if ((row.end_area || []).length === 1) {
        this.$message({
          message: "目的区域需要详细到市或区",
          type: "warning",
        });
        return false;
      }
      return true;
    },
    handleClickOperation(row, type) {
      if (type === "SAVE") {
        const flag = this.checkArea(row);
        if (!flag) {
          return;
        }
        row.start_area = row.start_area || [];
        row.end_area = row.end_area || [];
        row.start_area_province_id = row.start_area[0];
        row.start_area_city_id = row.start_area[1];
        row.start_area_district_id = row.start_area[2];
        row.end_area_province_id = row.end_area[0];
        row.end_area_city_id = row.end_area[1];
        row.end_area_district_id = row.end_area[2];
        row.billing_way = this.ruleForm.stepWay;
        row.ladder_range.forEach((range, index) => {
          range.min_measure = this.parseToNum(
            (this.ruleForm.rangeArr[index] || {}).min_measure
          );
          range.max_measure = this.parseToNum(
            (this.ruleForm.rangeArr[index] || {}).max_measure
          );
          range.ladder_price_list.forEach((priceItem) => {
            priceItem.based_on_price = this.parseToNum(
              priceItem.based_on_price
            );
            priceItem.further_price = this.parseToNum(priceItem.further_price);
            priceItem.first_measure = this.parseToNum(priceItem.first_measure);
          });
        });
        const fn =
          row.rowMode === "add"
            ? BillingRulePriceAddFn
            : BillingRulePriceUpdateFn;
        fn({
          billing_rule_id: this.ruleForm.id,
          ...row,
        }).then((res) => {
          if (res.code === 10000) {
            this.$set(row, "rowMode", "detail");
            this.getPriceListFn();
          }
        });
      } else if (type === "CANCEL") {
        this.$set(row, "rowMode", "detail");
        this.getPriceListFn();
      } else if (type === "EDIT") {
        console.log(row,'----0-000----')
        const startArea=row.start_area_district_id?[
          row.start_area_province_id,
          row.start_area_city_id,
          row.start_area_district_id,
        ]:[
          row.start_area_province_id,
          row.start_area_city_id,
        ]
        const endArea=row.end_area_district_id?[
          row.end_area_province_id,
          row.end_area_city_id,
          row.end_area_district_id,
        ]:[
          row.end_area_province_id,
          row.end_area_city_id,
        ]
        this.$set(row, "start_area", startArea);
        this.$set(row, "end_area", endArea);
        this.$set(row, "rowMode", "edit");
        console.log(row,'===row===')
      }
    },
    parseToNum(val) {
      if (Number.isNaN(val * 1)) {
        return 0;
      } else {
        return val * 1;
      }
    },
    //控制导入是否显示函数
    drawerfeesFlagShowFn(data) {
      this.importDialogShow = data;
    },
    async getDictionaryData() {
      let result = await getTransportsList({ is_all: false });
      this.transportTypeData = result.data.data;
      dictionanryList(["pricing_meth", "Package_model"]).then((res) => {
        // this.patternData = (res.data.list["pricing_meth"] || []).reverse();
        this.packageData = res.data.list["Package_model"];
      });
      regionList().then((res) => {
        const data = res.data || [];
        // data.forEach((item) => {
        //   item.next_level_data.forEach((iten) => {
        //     iten.next_level_data = undefined;
        //   });
        // });
        this.areaData = data;
      });
      carrierBox().then((res) => {
        this.carrierData = res.data;
      });
    },
    async getCustomerData(name) {
      if (name !== "") {
        let result3 = await customerPeople({
          name,
          is_send: "1",
        });
        this.customerData = result3.data;
      }
    },
    getCostName(index) {
      const [pid, cid] = this.ruleForm.pricing_range[index];
      for (let i = 0; i < this.rangeData.length; i++) {
        const rangeItem = this.rangeData[i];
        if (rangeItem.value === pid) {
          for (let j = 0; j < rangeItem.children.length; j++) {
            if (rangeItem.children[j].value === cid) {
              return rangeItem.children[j].label;
            }
          }
        }
      }
    },
    getLadderPriceItem(scope, index, indey1, priceItem) {
      scope.row["ladder_range"][index] = scope.row["ladder_range"][index] || {
        ladder_price_list: [],
      };

      let indey = (
        scope.row["ladder_range"][index].ladder_price_list || []
      ).findIndex((item) => item.cost_item_id == priceItem[1]);

      // scope.row['ladder_range'][index] = scope.row['ladder_range'][index] || { ladder_price_list: [] };
      // if (!scope.row['ladder_range'][index]['ladder_price_list'][indey]) {
      //     this.obj = {};
      //     this.$set(this.obj, 'based_on_price', '');
      //     this.$set(this.obj, 'first_measure', '');
      //     this.$set(this.obj, 'further_price', '');
      //     this.$set(this.obj, 'cost_item_id', 1);
      //     this.$set(scope.row['ladder_range'][index]['ladder_price_list'], indey, this.obj);
      // }
      // // console.log(indey, 'indey-----------');
      if (indey === -1) {
        indey = scope.row["ladder_range"][index]["ladder_price_list"].length;
        this.obj = {};
        this.$set(this.obj, "based_on_price", "");
        this.$set(this.obj, "first_measure", "");
        this.$set(this.obj, "further_price", "");
        this.$set(this.obj, "cost_item_id", priceItem[1]);
        this.$set(
          scope.row["ladder_range"][index]["ladder_price_list"],
          indey,
          this.obj
        );
      }
      // if (!scope.row['ladder_range'][index]['ladder_price_list'][indey]) {
      //     this.obj = JSON.parse(JSON.stringify(this.ladderPriceList))[indey];
      //     this.$set(scope.row['ladder_range'][index]['ladder_price_list'], indey, this.obj);
      // }
      return scope.row["ladder_range"][index]["ladder_price_list"][indey];

      // scope.row['ladder_range'] = scope.row['ladder_range'] || [];
      // scope.row['ladder_range'][index] = scope.row['ladder_range'][index] || {};
      // // this.$set(scope.row['ladder_range'], index, scope.row['ladder_range'][index] || {});
      // scope.row['ladder_range'][index]['ladder_price_list'] = scope.row['ladder_range'][index]['ladder_price_list'] || [];
      // // scope.row['ladder_range'][index]['ladder_price_list'][indey] = scope.row['ladder_range'][index]['ladder_price_list'][indey] || {};
      // this.$set(scope.row['ladder_range'][index][, indey, scope.row['ladder_range'][index]['ladder_price_list'][indey] || {});
      // return scope.row['ladder_range'][index]['ladder_price_list'][indey];
    },
    handleSelectionChange(checked) {
      this.checkedRow = checked.map((item) => item.area_id);
    },
    handleClickSubmit() {
      this.ruleForm.pricing_range = this.ruleForm._self_pricing_range;
      this.ruleForm.billing_way = this.ruleForm._self_billing_way;

      this.$refs["ruleForm"].validate((valid) => {
        if (!valid) return;
        // this.ruleForm.billing_area_price.forEach((item) => {
        //     item.start_area = item.start_area || [];
        //     item.end_area = item.end_area || [];
        //     item.start_area_province_id = item.start_area[0];
        //     item.start_area_city_id = item.start_area[1];
        //     item.end_area_province_id = item.end_area[0];
        //     item.end_area_city_id = item.end_area[1];
        //     item.billing_way = this.ruleForm.stepWay;
        //     item.ladder_range.forEach((range, index) => {
        //         range.min_measure = this.parseToNum((this.ruleForm.rangeArr[index] || {}).min_measure);
        //         range.max_measure = this.parseToNum((this.ruleForm.rangeArr[index] || {}).max_measure);
        //         range.ladder_price_list.forEach(priceItem => {
        //             priceItem.based_on_price = this.parseToNum(priceItem.based_on_price);
        //             priceItem.further_price = this.parseToNum(priceItem.further_price);
        //             priceItem.first_measure = this.parseToNum(priceItem.first_measure);
        //         });
        //     });
        // });
        // console.log(this.ruleForm);
        if (!this.ruleForm.id) {
          BillingRuleCreateFn(this.ruleForm).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "创建计费规则成功",
                type: "success",
              });
              this.ruleForm.id = res.data.id;
              this.$router.push({
                path: this.$route.path,
                query: { id: this.ruleForm.id },
              });
              this.getPriceListFn();
            }
          });
        } else {
          BillingRuleUpdateFn(this.ruleForm).then((res) => {
            if (res.code === 10000) {
              this.ruleForm._self_pricing_range = this.ruleForm.pricing_range;
              this.ruleForm._self_billing_way = this.ruleForm.billing_way;

              this.$message({
                message: "修改计费规则成功",
                type: "success",
              });
              this.getPriceListFn();
            }
          });
        }
      });
    },
    /**
     * 根据计费费项生成表格中的一行费项数据
     */
    generateLadderPriceList() {
      const ladder_price_list = [];

      this.ruleForm._self_pricing_range.forEach((item, index) => {
        ladder_price_list[index] = {
          cost_item_id: item[1],
          based_on_price: "",
          first_measure: "",
          further_price: "",
        };
      });
      this.ladderPriceList = JSON.parse(JSON.stringify(ladder_price_list));
    },
    // 计费费项发生变化
    handleChangeLimit(val) {
      if (Object.keys(val).length > 0) {
        this.generateLadderPriceList();
        // this.ruleForm.billing_area_price.forEach(item => {
        //     item.ladder_range.forEach(range => {
        //         range.ladder_price_list = this.mergeArrByCostId(JSON.parse(JSON.stringify(this.ladderPriceList)), range.ladder_price_list);
        //     });
        // });
      } else {
        // this.ruleForm.billing_area_price = [{
        //     ladder_range: [// 一个区间
        //         {
        //             ladder_price_list: [{}] // 一个费用项
        //         }]
        // }];
      }
    },
    mergeArrByCostId(arr1, arr2) {
      const mergedArr = (arr1 || []).map((item, index) => {
        const cost_item_id = item.cost_item_id;
        const meetItem =
          arr2.find((x) => x.cost_item_id === cost_item_id) || {};
        return { ...item, ...meetItem };
      });
      return mergedArr;
    },
    // 计费区间增删
    handleChangeRange(type) {
      const ladder_range_item = [];
      if (type === "ADD") {
        this.ruleForm.rangeArr.push({});
      } else if (type === "DELETE") {
        if (this.ruleForm.rangeArr.length > 1) {
          this.ruleForm.rangeArr.pop();
        }
      }
      this.priceList.forEach((item) => {
        if (type === "ADD") {
          item.ladder_range = item.ladder_range || [];
          item.ladder_range.push({
            ladder_price_list: JSON.parse(JSON.stringify(this.ladderPriceList)),
          });
        } else if (type === "DELETE") {
          item.ladder_range.pop();
        }
      });

      // this.ruleForm.rangeArr.forEach((item, index) => {
      //     ladder_range_item[index];
      // });
    },
    handleRangeChange(type, index) {
      const flag = this.checkId();
      if (!flag) {
        return;
      }
      if (type !== "add") {
        this.nowItem = JSON.parse(
          JSON.stringify(this.ruleForm.rangeArr[index])
        );
      }
      if (type === "add") {
        this.dialogVisible = true;
        this.rangeItem = {
          min_measure: "",
          max_measure: "",
        };
      } else if (type === "edit") {
        this.dialogVisible = true;
        this.rangeItem = {
          min_measure: this.nowItem.min_measure + "" || "",
          max_measure: this.nowItem.max_measure + "" || "",
        };
      } else if (type === "delete") {
        BillingRuleRangeDelete({
          billing_rule_id: this.ruleForm.id,
          min_measure: this.nowItem.min_measure + "",
          max_measure: this.nowItem.max_measure + "",
        }).then((res) => {
          if (res.code === 10000) {
            this.$message({
              message: "删除计费规则成功",
              type: "success",
            });
            this.getDetail();
          }
        });
      }

      this.dialogMode = type;
    },
    handleRangeOk() {
      this.$refs["rangeItem"].validate((valid) => {
        if (!valid) return;
        if (!this.ruleForm["stepWay"]) {
          this.$message({
            message: "请选择计费区间",
            type: "warning",
          });
          return;
        }
        if (this.dialogMode === "add") {
          BillingRuleRangeCreate({
            billing_rule_id: this.ruleForm.id, // 计费规则id
            billing_way: this.ruleForm["stepWay"],
            min_measure: this.rangeItem.min_measure + "",
            max_measure: this.rangeItem.max_measure + "",
          }).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "创建计费规则成功",
                type: "success",
              });
              this.dialogVisible = false;
              this.getDetail();
            }
          });
        } else if (this.dialogMode === "edit") {
          BillingRuleRangeUpdate({
            billing_rule_id: this.ruleForm.id, // 计费规则id
            billing_way: this.ruleForm["stepWay"],
            min_measure: this.rangeItem.min_measure + "",
            max_measure: this.rangeItem.max_measure + "",
            old_min_measure: this.nowItem.min_measure + "",
            old_max_measure: this.nowItem.max_measure + "",
          }).then((res) => {
            if (res.code === 10000) {
              this.$message({
                message: "修改计费规则成功",
                type: "success",
              });
              this.dialogVisible = false;
              this.getDetail();
            }
          });
        }
      });
    },
    checkId() {
      if (!this.ruleForm.id) {
        this.$alert("请先点击保存以上信息，保存后进行操作", "提示", {
          confirmButtonText: "确定",
          callback: (action) => { },
        });
        return false;
      }
      return true;
    },
    // tableRowClassName(row, index) {
    //     row.row.rowIndex = row.rowIndex;
    // },
    // 表格添加一行
    handleClickAdd() {
      // this.ruleForm.billing_area_price.push({
      //     ladder_range: [...Array(this.ruleForm.rangeArr.length)].map(x => {
      //         return { ladder_price_list: JSON.parse(JSON.stringify(this.ladderPriceList)) };
      //     })
      // });
      const flag = this.checkId();
      if (!flag) {
        return;
      }
      this.priceList.unshift({
        ladder_range: [...Array(this.ruleForm.rangeArr.length)].map((x) => {
          return {
            ladder_price_list: JSON.parse(JSON.stringify(this.ladderPriceList)),
          };
        }),
        min_charges:"",
        service_charge:"",
        return_incubator_fee_info: {
          "first_box_fee": "",
          "further_box_fee": "",
          "max_return_incubator_fee": ""
        },
        rowMode: "add",
      });
      // console.log(this.priceList, "priceList");
    },
    // 表格删除一行
    handleClickDel() {
      // this.ruleForm.billing_area_price = this.ruleForm.billing_area_price.filter(item => !this.checkedRow.includes(item.rowIndex));
      if (this.checkedRow.length === 0) {
        this.$message({
          message: "选中后才能进行操作",
          type: "warning",
        });
        return;
      }
      BillingRulePriceDeleteFn({
        area_ids: this.checkedRow,
      }).then((res) => {
        if (res.code === 10000) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          this.getPriceListFn();
        }
      });
    },
    handleClickImport() {
      const flag = this.checkId();
      if (!flag) {
        return;
      }
      // 一口价
      if (this.isFixedPrice) {
        this.downloadUrl =
          "https://dus-company-log-img.oss-cn-beijing.aliyuncs.com/undefined/1667297439356%E8%AE%A1%E8%B4%B9%E8%A7%84%E5%88%99%EF%BC%88%E4%B8%80%E5%8F%A3%E4%BB%B7%EF%BC%89%E5%AF%BC%E5%85%A5%E6%96%87%E4%BB%B6.xlsx";
      } else {
        this.downloadUrl =
          "https://dus-company-log-img.oss-cn-beijing.aliyuncs.com/undefined/1667297376036%E8%AE%A1%E8%B4%B9%E8%A7%84%E5%88%99%E5%AF%BC%E5%85%A5%E6%96%87%E4%BB%B6.xlsx";
      }
      this.importDialogShow = true;
    },
    getRangeArr() {
      if ((this.ruleForm.rangeArr || []).length > 0) {
        return this.ruleForm.rangeArr;
      } else {
        return [{}];
      }
    },
    handleClickExport() {
      const flag = this.checkId();
      if (!flag) {
        return;
      }
      BillingRuleExportFn({
        id: this.ruleForm.id, //规则id
        billing_way: this.ruleForm.billing_way,
      }).then((res) => {
        if (res.code === 10000) {
          this.reqUrl = "https://" + res.data.filename;
          window.open(this.reqUrl);
          // this.loadingfalse = false;
        }
      });
    },
    // 点击弹框提交导入
    handleImport(filename, cb) {
      const flag = this.checkId();
      if (!flag) {
        return;
      }
      BillingRuleImportFn({
        id: this.ruleForm.id, //规则id
        billing_way: this.ruleForm.billing_way,
        file_name: filename,
        header_id: "13",
      }).then((res) => {
        if (res.code === 10000) {
          cb(res || {});
          this.getDetail();
        }
      });
    },
    // 有效期变化
    handleChangeDate(val) {
      if (val) {
        this.ruleForm.start_time = val[0] / 1000;
        this.ruleForm.end_time = val[1] / 1000;
      }
    },
    // 计费方式变化
    handleWayChange() {
      if (this.isFixedPrice) {
        // this.priceList.forEach((item) => {
        //     item.ladder_range = item.ladder_range || [];
        //     item.ladder_range.forEach((range, index) => {
        //         range.ladder_price_list = range.ladder_price_list || [];
        //         range.ladder_price_list.forEach(priceItem => {
        //             priceItem.based_on_price = '';
        //             priceItem.further_price = '';
        //             priceItem.first_measure = '';
        //         });
        //     });
        // });
      }
    },
    handleBack() {
      this.$router.go(-1);
    },
    /**
     * 获取阶梯区间数据
     */
    getPriceListFn() {
      BillingRulePriceListFn({
        billing_rule_id: this.ruleForm.id, // 计费规则id
        page: this.paginations.pageIndex,
        page_size: this.paginations.pageSize,
      }).then((res) => {
        this.priceList = res.data.list || [];
        this.paginations.total = res.data.pagination.total;
        if (this.priceList[0]) {
          const item = this.priceList[0];
          const rangeArr = item.ladder_range.map((item) => {
            return {
              max_measure: item.max_measure * 1,
              min_measure: item.min_measure * 1,
            };
          });
          this.$set(this.ruleForm, "rangeArr", rangeArr);
          this.$set(this.ruleForm, "stepWay", item.billing_way);
          if ((this.ruleForm["rangeArr"] || []).length === 0) {
            this.$set(this.ruleForm, "rangeArr", []);
          }
        } else {
          this.$set(this.ruleForm, "rangeArr", []);
        }
      });
    },
    // 每页条数改变
    handleSizeChange(val) {
      this.paginations.pageSize = val;
      if (this.ruleForm.id) {
        this.getPriceListFn();
      }
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.paginations.pageIndex = val;
      if (this.ruleForm.id) {
        this.getPriceListFn();
      }
    },
    getTitleTip() {
      const { mode } = this;
      if (mode === "add") {
        return "新建计费规则";
      } else if (mode === "edit") {
        return "编辑计费规则";
      } else {
        return "计费规则详情";
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.charging_rules {
  padding: 10px;
  margin-top: 5px;
  margin-left: 5px;
  background-color: #fff;

  .range_select {
    float: left;
    margin-right: 10px;
    margin-bottom: 5px;
  }

  .range_input {
    float: left;
    // margin-right: 10px;
    margin-bottom: 5px;

    .el-input {
      width: 80px !important;
    }
  }

  .range_icon {
    float: left;

    i {
      font-size: 24px;
      margin-right: 10px;
    }

    .bgcolor {
      color: red;
    }
  }

  /deep/.price_input .el-input--suffix .el-input__inner {
    padding-right: 15px !important;
  }

  .actions {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    width: 100%;
    background-color: #fff;
  }
}

.range_tab {
  width: 100%;
  height: 30px;
  background: #f2f3f5;
  font-weight: bold;
  line-height: 30px;
  padding-left: 12px;
  margin-bottom: 16px;
  color: #6d6e72;
  font-size: 14px;
}

.rule_title {
  // background: red;
  display: flex;
  align-items: center;
  padding-bottom: 18px;
  padding-top: 8px;
  font-size: 14px;
  font-weight: bold;
  justify-content: space-between;

  .title-l {
    display: flex;
    align-items: center;
  }

  .icon_left {
    display: inline-block;
    width: 6px;
    height: 16px;
    background: #f1a357;
    margin-right: 6px;
  }

  .icon-right {
  }
}

.btn_save {
  // display: flex;
  // justify-content: center;
  padding: 30px 0;

  .btn_save_content {
    display: flex;
    justify-content: center;
    flex-direction: column;
    align-items: center;
    color: #606266;
    font-size: 12px;
  }
}
</style>
